package com.rain.shoppingscienceproj.ui.activity.address;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;

import com.rain.shoppingscienceproj.R;
import com.rain.shoppingscienceproj.http.BaseSubscriber;
import com.rain.shoppingscienceproj.http.ExceptionHandle;
import com.rain.shoppingscienceproj.http.RetrofitClient;
import com.rain.shoppingscienceproj.module.Address;
import com.rain.shoppingscienceproj.ui.activity.BaseActivity;
import com.rain.shoppingscienceproj.ui.activity.login.LoginActivity;
import com.rain.shoppingscienceproj.ui.adapter.AddressAdapter;
import com.rain.shoppingscienceproj.ui.base.GlobalData;
import com.rain.shoppingscienceproj.ui.utile.DialogUtils;
import com.rain.shoppingscienceproj.ui.utile.TitleUtils;
import com.rain.shoppingscienceproj.utils.AppManager;
import com.rain.shoppingscienceproj.utils.LoadingDialog;
import com.rain.shoppingscienceproj.utils.toast.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;

public class ShowAddressActivity extends BaseActivity {


    @BindView(R.id.recycler_address)
    RecyclerView mRecyclerView;
    private AddressAdapter adapter;
    @BindView(R.id.ll_no_data)
    LinearLayout ll_no_data;

    int type = 0;

    @OnClick(R.id.rl_right)
    void address() {
        startActivitys(AddressActivity.class);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_address);
        AppManager.getAppManager().addActivity(this);
        ButterKnife.bind(this);
        type = getIntent().getIntExtra("type", 0);
        if (type == 1) {
            TitleUtils.TitleView(this, "选择收货地址");
        } else {
            TitleUtils.TitleRightText(this, "我的收货地址", "添加新地址");
            TitleUtils.mRightText.setTextColor(getResources().getColor(R.color.white));
        }
        loadingDialog = new LoadingDialog(this, "正在加载...");
        userInfo = GlobalData.getUserInfo();
        initView();
        initData();
        initListener();
    }

    private void initListener() {
        adapter.setLongItemListener((addressData, position) -> {
            DialogUtils.dialog(this, "确定删除该地址吗?");
            DialogUtils.getTv_sure().setOnClickListener(v -> delAdd(addressData));
        });

        adapter.setOnItemClickListener(addressData -> {
            if (type == 1) {
                Intent intent = new Intent();
                intent.putExtra("address", addressData);
                setResult(type, intent);
                finish();
            }
        });
    }

    private void delAdd(Address addressData) {
        Map<String, String> map = new HashMap<>();
        map.put("addressId", addressData.getAddressId());
        map.put("token", userInfo.getToken());
        loadingDialog.show();
        RetrofitClient.getInstance(this)
                .createBaseApi()
                .delAdress(map, new BaseSubscriber<ResponseBody>(this) {
                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable e) {
                        ToastUtils.showShortToast("网络错误");
                        loadingDialog.dismiss();
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        super.onNext(responseBody);
                        loadingDialog.dismiss();
                        try {
                            String request = responseBody.string();
                            JSONObject json = new JSONObject(request);
                            int code = json.getInt("code");
                            DialogUtils.dismissDialog();
                            if (code == 0) {
                                ToastUtils.showShortToast(json.getString("message"));
                                initData();
                            } else {
                                ToastUtils.showShortToast(json.getString("message"));
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        initData();
    }

    private void initData() {
        Map<String, String> map = new HashMap<>();
//        map.put("userId", userInfo.getUserId());
        map.put("token", userInfo.getToken());
        loadingDialog.show();
        RetrofitClient.getInstance(this)
                .createBaseApi()
                .queryAddress(map, new BaseSubscriber<List<Address>>(this) {
                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable e) {
                        if (e.Message.contains("token")) {
                            startActivitys(LoginActivity.class, 1);
                        }
                        ll_no_data.setVisibility(View.VISIBLE);
                        mRecyclerView.setVisibility(View.GONE);
                        loadingDialog.dismiss();
                    }

                    @Override
                    public void onNext(List<Address> addresses) {
                        super.onNext(addresses);
                        if (addresses.size() == 0) {
                            ll_no_data.setVisibility(View.VISIBLE);
                            mRecyclerView.setVisibility(View.GONE);
                        } else {
                            ll_no_data.setVisibility(View.GONE);
                            mRecyclerView.setVisibility(View.VISIBLE);
                        }
                        loadingDialog.dismiss();
                        adapter.setList(addresses);
                    }
                });

    }

    private void initView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new AddressAdapter(this, 2);
        mRecyclerView.setAdapter(adapter);
    }
}
